/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.training.service.impl;


import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.DeptBean;
import com.koron.common.domain.DataBean;
import com.koron.common.web.Util;
import com.koron.personal.domain.MyCertificate;
import com.koron.personal.mapper.MyCertificateMapper;
import com.koron.system.domain.DictData;
import com.koron.system.mapper.DictDataMapper;
import com.koron.training.domain.PersonnalCertification;
import com.koron.training.mapper.MatrixMapper;
import com.koron.training.service.api.MatrixService;
import com.koron.training.utils.BusinessCode;
import org.apache.commons.collections4.map.LinkedMap;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MatrixServiceImpl implements MatrixService {
    private final static  Logger logger = LoggerFactory.getLogger(MatrixServiceImpl.class);

    @Autowired
    private Util util;

    @Override
    public MessageBean<?> queryDutyCetificate(String dutiesId, String corpCode, String name, Integer start, Integer rows) {
        MessageBean<Map> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "证照矩阵查询成功", Map.class);
        try (SessionFactory factory = new SessionFactory()) {
            Map<String, Object> map = new LinkedMap<>();
            List<DictData> ddlist = factory.getMapper(DictDataMapper.class).queryAll(null, "certificate_type", null, null);
            if (null == ddlist || ddlist.size() <= 0) {
                return msg;
            }
            List<String> nameList = ddlist.stream().map(DictData::getDictLabel).collect(Collectors.toList());
            map.put("nameList", nameList);
            List<Map<String, Object>> maps = factory.getMapper(MatrixMapper.class).queryDutyCetificate(ddlist, dutiesId, corpCode, name, start, rows);
            List<Map<String, Object>> map1 = factory.getMapper(MatrixMapper.class).queryDutyCetificate(ddlist, dutiesId, corpCode, name, null, null);
            int totalNumber = 0, totalPage = 1, page = 1;
            if (map1 != null && !map1.isEmpty()) {
                totalNumber = map1.size();
            }
            rows = (rows <= 0 || rows == null) ? totalNumber : rows;
            if (totalNumber > 0) {
                totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            }
            if (start > 0) {
                page = start / rows;
            }
            map.put("matrix", maps);
            map.put("totalNumber", totalNumber);
            map.put("totalPage", totalPage);
            map.put("pageSize", rows);
            map.put("page", page);
            msg.setData(map);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Map> exportDutyCetificate(String corpCode, String name, String dutiesId) {
        MessageBean<Map> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "证照矩阵查询成功", Map.class);
        try (SessionFactory factory = new SessionFactory()) {
            LinkedHashMap<String, Object> map = new LinkedHashMap<>();
            List<DictData> ddlist = factory.getMapper(DictDataMapper.class).queryAll(null, "certificate_type", null, null);
            if (null == ddlist || ddlist.size() <= 0) {
                return msg;
            }
            List<String> nameList = ddlist.stream().map(DictData::getDictLabel).collect(Collectors.toList());
            map.put("nameList", nameList);
            List<Map<String, Object>> maps = factory.getMapper(MatrixMapper.class).queryDutyCetificate(ddlist, dutiesId, corpCode, name, null, null);
            map.put("matrix", maps);
            msg.setData(map);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<PersonnalCertification>> queryPersonalCertification(String corpCode, String staffName, String dutyName, String certificateName,
                                                                                    String deptCode, Integer status, Integer start, Integer rows) {
        MessageBean<DataBean<PersonnalCertification>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (null != status) {
                if (0 != status && 2 != status && 1 != status) {
                    msg.setCode(BusinessCode.ILLEGAL_PARAM.getCode());
                    msg.setDescription(BusinessCode.ILLEGAL_PARAM.getDescription());
                    return msg;
                }
            }
            List<String> corpCodeList = new ArrayList<>();
            //查询当前部门及下属所有部门的持证情况
            List<DepartmentTreeBean> departmentTreeBeanList = (List<DepartmentTreeBean>) util.depttree(corpCode, 1).getData();
            if (null != departmentTreeBeanList && departmentTreeBeanList.size() > 0) {
                corpCodeList = departmentTreeBeanList.stream().map(DepartmentTreeBean::getDepartmentCode).collect(Collectors.toList());
            } else {
                corpCodeList.add(corpCode);
            }
            Date time = new Date();
            List<PersonnalCertification> newList = new ArrayList<>();
            List<PersonnalCertification> list = factory.getMapper(MatrixMapper.class).queryPersonalCertification(corpCodeList, staffName, dutyName, certificateName, deptCode, status, time);
            newList.addAll(list);
            //过滤与个人证照关联的数据
            List<PersonnalCertification> dutyRelationList = list.stream().filter(item -> StringUtils.isNotBlank(item.getMyCertificateId())).collect(Collectors.toList());
            List<String> myCertificateIdList = dutyRelationList.stream().map(PersonnalCertification::getMyCertificateId).collect(Collectors.toList());
            if (null == myCertificateIdList || myCertificateIdList.size() <= 0) {
                myCertificateIdList = new ArrayList<>();
            }
            //查询所有的个人证照列表数据
            List<MyCertificate> myCertificateList = factory.getMapper(MyCertificateMapper.class).queryByCondition(null, null, null,null);
            //找出没有与岗位相关的上传的证件-即用户私底下上传的证件
            List<String> idList = myCertificateList.stream().map(MyCertificate::getId).collect(Collectors.toList());
            //将只上传与岗位无关证照的用户code过滤出来
            List<String> newIdList = new ArrayList<>();
            for (String id : idList) {
                if (!myCertificateIdList.contains(id)) {
                    newIdList.add(id);
                }
            }
            if (newIdList != null && newIdList.size() > 0) {
                List<MyCertificate> newMyCertificateList = factory.getMapper(MyCertificateMapper.class).queryCetificateByIdList(newIdList, corpCodeList, staffName, dutyName, certificateName, deptCode, status, time);
                if (null != newMyCertificateList && newMyCertificateList.size() > 0) {
                    for (MyCertificate c : newMyCertificateList) {
                        PersonnalCertification certification = new PersonnalCertification();
                        certification.setStaffName(c.getStaffName());
                        certification.setJobsStaffCertificateId(c.getJobsStaffCertificateId());
                        certification.setDeptCode(c.getDeptCode());
                        certification.setDutyName(c.getDutiesName());
                        certification.setPeriod(c.getPeriod());
                        certification.setCertificateName(c.getCertificateName());
                        certification.setStaffCode(c.getStaffCode());
                        certification.setMyCertificateId(c.getId());
                        newList.add(certification);
                    }
                }
            }
            Integer totalNumber = newList.size();
            rows = (rows == null || rows <= 0) ? 1 : rows;
            Integer totalPage = totalNumber > rows ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
//            Integer end = (start == 0 ? 1 : start) + rows;
            Integer end = start + rows;
            List<PersonnalCertification> realList = new ArrayList<>();
            if (status != null) {
                if (status == 0) {
                    realList = newList.stream().filter(item -> item.getPeriod().compareTo(time) >= 0).collect(Collectors.toList());
                } else if (status == 1) {
                    realList = newList.stream().filter(item -> item.getPeriod().compareTo(time) < 0).collect(Collectors.toList());
                } else if (status == 2) {
                    realList = newList.stream().filter(item -> item.getPeriod() == null).collect(Collectors.toList());
                }
            } else {
                realList = newList;
            }
            if (end > realList.size()) {
                end = realList.size();
                if (start > end) {
                    start = end;
                }
            }
            int pageNo = 1;
            if (start > 0) {
                pageNo = start * rows;
            }
            realList.subList(start, end).forEach(item -> getNames(item));
            DataBean<PersonnalCertification> dataBean = new DataBean<>();
            dataBean.setList(realList.subList(start, end));
            dataBean.setTotalNumber(totalNumber);
            dataBean.setPageSize(rows);
            dataBean.setTotalPage(totalPage);
            dataBean.setPageNo(pageNo);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取人员持证列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<List<PersonnalCertification>> exportPersonalCertification(String corpCode, String staffName, String dutyName, String certificateName,
                                                                                 String deptCode, Integer status) {
        MessageBean<List<PersonnalCertification>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (null != status) {
                if (0 != status && 2 != status && 1 != status) {
                    msg.setCode(BusinessCode.ILLEGAL_PARAM.getCode());
                    msg.setDescription(BusinessCode.ILLEGAL_PARAM.getDescription());
                    return msg;
                }
            }
            List<String> corpCodeList = new ArrayList<>();
            //查询当前部门及下属所有部门的持证情况
            List<DepartmentTreeBean> departmentTreeBeanList = (List<DepartmentTreeBean>) util.depttree(corpCode, 1).getData();
            if (null != departmentTreeBeanList && departmentTreeBeanList.size() > 0) {
                corpCodeList = departmentTreeBeanList.stream().map(DepartmentTreeBean::getDepartmentCode).collect(Collectors.toList());
            } else {
                corpCodeList.add(corpCode);
            }
            Date time = new Date();
            List<PersonnalCertification> newList = new ArrayList<>();
            List<PersonnalCertification> list = factory.getMapper(MatrixMapper.class).queryPersonalCertification(corpCodeList, staffName, dutyName, certificateName, deptCode, status, time);
            newList.addAll(list);
            //过滤与个人证照关联的数据
            List<PersonnalCertification> dutyRelationList = list.stream().filter(item -> StringUtils.isNotBlank(item.getMyCertificateId())).collect(Collectors.toList());
            List<String> myCertificateIdList = dutyRelationList.stream().map(PersonnalCertification::getMyCertificateId).collect(Collectors.toList());
            if (null == myCertificateIdList || myCertificateIdList.size() <= 0) {
                myCertificateIdList = new ArrayList<>();
            }
            //查询所有的个人证照列表数据
            List<MyCertificate> myCertificateList = factory.getMapper(MyCertificateMapper.class).queryByCondition(null, null, null,null);
            //找出没有与岗位相关的上传的证件-即用户私底下上传的证件
            List<String> idList = myCertificateList.stream().map(MyCertificate::getId).collect(Collectors.toList());
            //将只上传与岗位无关证照的用户code过滤出来
            List<String> newIdList = new ArrayList<>();
            for (String id : idList) {
                if (!myCertificateIdList.contains(id)) {
                    newIdList.add(id);
                }
            }
            if (newIdList != null && newIdList.size() > 0) {
                List<MyCertificate> newMyCertificateList = factory.getMapper(MyCertificateMapper.class).queryCetificateByIdList(newIdList, corpCodeList, staffName, dutyName, certificateName, deptCode, status, time);
                if (null != newMyCertificateList && newMyCertificateList.size() > 0) {
                    for (MyCertificate c : newMyCertificateList) {
                        PersonnalCertification certification = new PersonnalCertification();
                        certification.setStaffName(c.getStaffName());
                        certification.setJobsStaffCertificateId(c.getJobsStaffCertificateId());
                        certification.setDeptCode(c.getDeptCode());
                        certification.setDutyName(c.getDutiesName());
                        certification.setPeriod(c.getPeriod());
                        certification.setCertificateName(c.getCertificateName());
                        certification.setStaffCode(c.getStaffCode());
                        certification.setMyCertificateId(c.getId());
                        newList.add(certification);
                    }
                }
            }
            newList.forEach(item -> getNames(item));
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取人员持证列表成功");
            msg.setData(newList);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }


    private void getNames(PersonnalCertification bean) {
        if (bean != null) {
            if (StringUtils.isNotEmpty(bean.getStaffCode())) {
                List<DeptBean> deptBeanList = (List<DeptBean>) util.dept(bean.getStaffCode().split("_")[0]).getData();
                if (null != deptBeanList && !deptBeanList.isEmpty()) {
                    bean.setDeptName(deptBeanList.get(0).getName());
                }
            }
        }
    }
}
